import datetime
import json
import random
import re
from collections import defaultdict
import ddddocr
import requests
import logging
from encrypto import AESCipher
from util_date import DATE_FORMAT
from utils_mail import send_alert

employee_reports = []
logger = logging.getLogger('my_logger')


def get_captcha():
    # 降级Pillow的版本，比如使用9.5.0版本
    while True:
        r = requests.get('https://yunji-web.sxidc.com/api/common/captcha')
        resp = r.json()
        image_data = resp['infos']['CaptchaB64s']
        captcha_id = resp['infos']['CaptchaId']
        header, content = image_data.split(",", 1)
        ocr = ddddocr.DdddOcr()
        captcha = ocr.classification(content)
        # 使用正则表达式从字符串变量中提取个位数加减乘除的算式
        pattern = r'\d+[+\-]\d'
        matches = re.findall(pattern, captcha)
        if len(matches) > 0:
            break
    calculated_result = eval(matches[0])
    return captcha_id, matches[0], str(calculated_result)


def login_in(username, password):
    url = 'https://yunji-web.sxidc.com/api/ngum/user/login/common'
    access_token = None
    while True:
        captcha_id, matches, calculated_result = get_captcha()
        data = {
            "username": username,
            "password": password,
            "verificationCode": calculated_result,
            "captchaId": captcha_id
        }
        response = requests.post(url, json=data)
        if response.status_code == 200:
            response_data = response.json()
            if "success" in response_data and response_data["success"]:
                if "info" in response_data:
                    access_token = response_data["info"]["accessToken"]
                    break
                else:
                    logger.error("JSON响应中没有accessToken字段")
                    continue
            else:
                logger.error("请求成功，但success字段为False")
                continue
    logger.info('access_token=' + access_token)
    key = '@MKU^AAOTF%K^#VJ<TAHCVD#$XZSWQ@L'
    iv = '@MKU^AAOTF%K^#VJ'
    # , ut = "@MKU^"
    # , dt = "AAOTF%K^#VJ"
    #   no = "<TAHCVD#$XZSWQ@L"
    # , qo = `${ut}${dt}${no}
    # `
    # , jo = `${ut}${dt}
    # `
    # 创建加密对象
    e = AESCipher(key, iv)
    enc_str = e.aes_encrypt(access_token)
    logger.info('enc_str=' + enc_str)
    return enc_str


# 查询考勤结果
def query_attendance(access_token, offset):
    url = 'https://yunji-web.sxidc.com/api/v1/as/user/statistic'
    headers = {
        'Authorization': access_token
    }
    params = {
        'offset': offset
    }
    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()
    return response.json()


def is_check_in(access_token):
    resp_json = query_attendance(access_token, 0)
    not_check = resp_json["notCheck"]
    checked = resp_json["checked"]
    # 判断当天是否上班
    if len(checked) <= len(not_check):
        return
    for emp in not_check:
        if emp["name"] == "杨楷":
            send_alert("未检测到有效上班卡", "")


def is_check_out(access_token):
    resp_json = query_attendance(access_token, 0)
    not_check = resp_json["notCheck"]
    checked = resp_json["checked"]
    # 判断当天是否上班
    if len(checked) <= len(not_check):
        return
    for emp in not_check:
        if emp["name"] == "杨楷":
            return
    compare_time = datetime.date.today().strftime(DATE_FORMAT) + " 18:30:00"
    for emp in checked:
        if emp["name"] == "杨楷":
            if len(emp["lastCheckIn"]) > 0 and emp["lastCheckIn"] > compare_time:
                return
    send_alert("未检测到有效下班卡", "")


# logDate=2023-11-09&memberId=10a1d9292efc4a8c8dc6c631df91e1c5
def get_daily_report(access_token, **params):
    url = 'https://yunji-web.sxidc.com/api/v1/workReportDaily/simple/query'
    headers = {
        'Authorization': access_token
    }
    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()
    report_list = response.json()["infos"]
    if len(report_list) == 0:
        return []
    ids = []
    for report in report_list:
        ids.append(report["id"])
    return ids


def review_and_evaluate_daily_report(access_token, ids, name):
    review_url = 'https://yunji-web.sxidc.com/api/v1/workReportDaily/review'
    evaluate_url = "https://yunji-web.sxidc.com/api/v1/workReportDaily/evaluate"
    headers = {
        'Authorization': access_token
    }
    tinydict = {}
    evaluate_param = json.loads(
        "{\"workReportId\":\"9d36b17a590341dcb15be8b246cd85e3\",\"remark\":\"\",\"scores\":[{\"itemName\":\"工时准确性\",\"score\":0},{\"itemName\":\"工作完成质量\",\"score\":0},{\"itemName\":\"工作效率\",\"score\":0},{\"itemName\":\"反馈情况\",\"score\":0},{\"itemName\":\"工作态度\",\"score\":0}],\"recordId\":\"\"}")
    random_numbers = [random.randint(2, 4) for _ in range(4)]
    for i in range(4):
        evaluate_param["scores"][i]["score"] = random_numbers[i]
    for id in ids:
        tinydict["reportId"] = id
        evaluate_param["workReportId"] = id
        response_review = requests.post(review_url, headers=headers, json=tinydict)
        response_review.raise_for_status()
        response_evaluate = requests.post(evaluate_url, headers=headers, json=evaluate_param)
        response_evaluate.raise_for_status()


def recursive_json(json_data):
    if isinstance(json_data, dict):  # 如果是字典类型
        for key, value in json_data.items():
            if isinstance(value, (dict, list)) and key != "orgUsers":  # 如果value是字典或列表类型
                recursive_json(value)  # 递归调用自身
            elif key == "orgUsers":
                global employee_reports
                employee_reports.extend(value)
    elif isinstance(json_data, list):  # 如果是列表类型
        for item in json_data:
            recursive_json(item)  # 递归调用自身


def get_report(access_token, logDate, args):
    url = 'https://yunji-web.sxidc.com/api/v1/workReportDaily/simple/query'
    headers = {
        'Authorization': access_token
    }
    params = {
        'logDate': logDate,
        'memberId': ''
    }
    report_list_all = []
    for arg in args:
        params['memberId'] = arg
        response = requests.get(url, headers=headers, params=params)
        response.raise_for_status()
        report_list_all.extend(response.json()["infos"])
    grouped_object = defaultdict(list)
    for report in report_list_all:
        grouped_object[report["memberName"]].append(report)
    emp_report_dict = {}
    for key, value_list in grouped_object.items():
        empty_str = ''
        for v in value_list:
            empty_str = empty_str + f"[{v['projectName']}({v['duration']})]\n{v['actual']}{v['createAt']}\n"
        emp_report_dict[key] = empty_str
    return emp_report_dict


# 上一个工作日日报填报情况及部门工作详情
def getReportDetails(access_token):
    # 签到
    # requests.post("https://yunji-wechat.sxidc.com/mbwcb/api/v1/bpa/sign/in", headers={'Authorization': access_token})
    # 判断上一个工作日
    today = datetime.date.today()
    last_week_day = None
    for i in range(1, 11):
        resp_json = query_attendance(access_token, -i)
        not_check = resp_json["notCheck"]
        checked = resp_json["checked"]
        if len(checked) >= len(not_check):
            last_week_day = today - datetime.timedelta(days=i)
            break
    url = 'https://yunji-web.sxidc.com/api/v1.1/workReportDaily/org/query'
    headers = {
        'Authorization': access_token
    }
    params = {
        'logDate': last_week_day
    }
    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()
    report_list = response.json()["infos"]
    global employee_reports
    # 所有员工日报概览
    employee_reports = []
    recursive_json(report_list)
    # 未写日报人员
    none_of_report_emp = []
    for emp in employee_reports:
        if emp["writeFlag"] != True:
            none_of_report_emp.append(emp["name"])
    # 职能&财务
    emps = ["2d53723d31424e199e765db602355ba6", "35c76b8a070f45a694f17194166f7f06", "10362bfd89a747ee8baee64190da1adc",
            "163a613639c14bcbb3f0009e49ebe9b5", "03d56f253d0a46fbb5a1ea17d62a1318", "b38983f122de4e7f9609db05c31068fa",
            "62c7899c81424ddbaa67e3dbbcc6515e", "7199eb64e23a490684520ff3434f879b", "d7cc9b043e1542cda477ad7b5bcd921c",
            "af12ecfd85954095804343645e78b27c", "33cd67b50e0045d3a0f7a7bfe6fef4d2"]
    dict = get_report(access_token, last_week_day, emps)
    # 总人数，未写日报人员,关注人员日报列表
    return len(employee_reports), none_of_report_emp, dict


# 签到
def check_in(access_token):
    requests.post("https://yunji-wechat.sxidc.com/mbwcb/api/v1/bpa/sign/in", headers={'Authorization': access_token})


if __name__ == '__main__':
    #
    obj = login_in('yangkai', 'aruEZ4HNa2bVEtC')
    print(obj)
    print(is_check_out(obj))
    print(get_daily_report(obj, logDate='2024-05-15', memberId="7c4c52e88af1455696cd39dd5a7fbf7f"))
#     proxies = {
#         'http': 'socks5://yyqqm2:yyqqm3@5.231.88.249:6804',
#         'https': 'socks5://yyqqm2:yyqqm3@5.231.88.249:6804'
#     }
#
#     response = requests.get('http://cip.cc.com', proxies=proxies)
#     print(response.text)
#     jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiI3YzRjNTJlODhhZjE0NTU2OTZjZDM5ZGQ1YTdmYmY3ZiIsImV4cCI6MTcwMDAxNzU4OCwiaWF0IjoxNjk5OTMxMTg4fQ.sPCjpa0pWAoQGHwQNDANGJaK_LD2ngVF0zw3lH62NSg"
#     response2 = requests.post("https://yunji-wechat.sxidc.com/mbwcb/api/v1/bpa/sign/in", headers={'Authorization': jwt})
#     print(response.json())
